<template>
    <div class="common">
      <div class="login">
        <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
    class="demo-ruleForm"
    :size="formSize"
    status-icon
  >
    <el-form-item label="用户名" prop="name">
            <el-input v-model="ruleForm.name" />
    </el-form-item>
   
    <el-form-item label="密码" prop="password">
            <el-input v-model="ruleForm.password"  type="password"/>
    </el-form-item>

    <el-form-item style="margin-left: 150px;">
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        登录
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
    </div></div>
</template>

<script>
import router from '@/router';
import axios from 'axios';

export default {
  data() {
    return {
      formSize: 'default',
      ruleForm: {
        name: '',
        
      },
      locationOptions: ['Home', 'Company', 'School'],
      options: Array.from({ length: 10000 }, (_, idx) => ({
        value: `${idx + 1}`,
        label: `${idx + 1}`,
      })),
      rules: {
        name: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 8, message: '长度必须是3-8', trigger: 'blur' },
        ],     
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 10, message: '长度必须是3-10', trigger: 'blur' },
        ],         
      },
      ruleFormRef: null,
      userslist:[]
    };
  },
  methods: {
    submitForm() {
      this.$refs.ruleFormRef.validate((valid, fields) => {
        if (valid) {
          //在此处创建代码完成用户的认证
          //在使用some方法对数组进行便利，查找到符合的数据，如果找到了，则返回true，否则返回false
          
          let flag =this.userslist.some(v=>v.name==this.ruleForm.name && v.password==this.ruleForm.password)
          if(!flag){
            alert("请输入正确的用户名和密码")
          }else{
            //跳转到首页，在跳转之前，先把用户名保存在sessionstorage中
            sessionStorage.setItem("username",this.ruleForm.name)
            router.push('/')
          }
          console.log('submit!');
        } else {
          console.log('error submit!', fields);
        }
      });
    },
    resetForm() {
      this.$refs.ruleFormRef.resetFields();
    },
  },
  mounted() {
    this.ruleFormRef = this.$refs.ruleFormRef;
    axios.get('userslist.json').then(res=>{
      this.userslist=res.data.userslist
      // console.log(res.data.userslist);

    })
  },
};
</script>


<style>
.common{
    background: url('../../assets/1.png');
    height: 100%;
    width: 100%;
    display: flex;
    background-size: cover;
    position: absolute;
    top: 0;
    left: 0;

}
.login{
  width: 400px;
  height: 200px;
  margin-top: 300px;
  margin-left: 250px;
}
</style>